package com.zretc.emptraining.daoimpl;

import java.util.List;

import com.zretc.emptraining.dao.DeptDao;
import com.zretc.emptraining.dbtools.DBTools;
import com.zretc.emptraining.dbtools.PageData;
import com.zretc.emptraining.entity.Dept;

public class DeptDaoImpl implements DeptDao {

	@Override
	public boolean addDept(Dept dept) {
		if(dept != null) {
			String sql = "insert into dept values(?,?,?)";
			return DBTools.getUpdate(sql, dept.getDeptNo(),dept.getDeptName(),dept.getEmpNo()) > 0;
		}
		return false;
	}
	
	@Override
	public boolean addDeptNoManager(Dept dept) {
		if(dept != null) {
			String sql = "insert into dept values(?,?,null)";
			return DBTools.getUpdate(sql, dept.getDeptNo(),dept.getDeptName()) > 0;
		}
		return false;
	}

	@Override
	public boolean delDeptByDeptNo(int deptno) {
		if(deptno > 0) {
			String sql = "delete from dept where deptNo = ?";
			return DBTools.getUpdate(sql, deptno) > 0;
		}
		return false;
	}

	@Override
	public boolean updDept(Dept dept) {
		if(dept != null) {
			String sql = "update dept set deptName = ? , empNo = ? where deptNo = ?";
			return DBTools.getUpdate(sql, dept.getDeptName(),dept.getEmpNo(),dept.getDeptNo()) > 0;
		}
		return false;
	}

	@Override
	public Dept getDeptByDeptName(String deptname) {
		String sql = "select * from dept where deptName = ?";
		List<Dept> list = (List<Dept>) DBTools.exQuery(sql, Dept.class, deptname);
		if(list.size() == 0) {
			return null; 
		}
		return list.get(0);
	}
	
	@Override
	public Dept getDeptByDeptNo(int deptno) {
		String sql = "select * from dept where deptNo = ?";
		List<Dept> list = (List<Dept>) DBTools.exQuery(sql, Dept.class, deptno);
		if(list.size() == 0) {
			return null; 
		}
		return list.get(0);
	}
	
	@Override
	public Dept getDeptByEmpNo(int empno) {
		String sql = "select * from dept where empNo = ?";
		List<Dept> list = (List<Dept>) DBTools.exQuery(sql, Dept.class, empno);
		if(list.size() == 0) {
			return null; 
		}
		return list.get(0);
	}
	
	@Override
	public PageData<Dept> getPageByDeptName(int page , int pageSize , String deptname) {
		String sql = "SELECT d.deptNo,d.deptName,d.empNo,e.empName\r\n" + 
				"FROM dept d LEFT JOIN emp e\r\n" + 
				"ON d.empNo = e.empNo WHERE deptName like ?";
		PageData<Dept> pd = DBTools.exQueryByPage(sql, Dept.class, page, pageSize , "%"+deptname+"%");
		return pd;
	}
	
	@Override
	public List<Dept> getAllDept(String key) {
		String sql = "select * from dept where deptName like ?";
		List<Dept> list = (List<Dept>) DBTools.exQuery(sql, Dept.class, "%"+key+"%");
		return list;
	}

}
